<template>
  <div class="add-wrapper">
    <div class="fixed-btn" @click="() => popupShow = true">+</div>
    <van-popup v-model:show="popupShow" position="bottom" round>
      <div class="content-wrapper">
        <textarea placeholder="请输入要干的大事吧~" v-model="content" />
        <div class="footer">
          <div class="end-time" @click="() => showDatePoput = true"><van-icon name="clock-o" style="margin-right:3px" /> {{stopDate ? dateFormat(stopDate) : '截止时间'}}</div>
          <div>
            <button @click="() => popupShow = false">取消</button>
            <button class="save" @click="onSave">保存</button>
          </div>
        </div>
      </div>
    </van-popup>
    <van-popup v-model:show="showDatePoput" position="bottom" round>
      <van-datetime-picker
        v-model="stopDate"
        type="datetime"
        title="选择截止时间"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="() => showDatePoput = false"
        @confirm="onDateConfirm"
      />
    </van-popup>
  </div>
</template>

<script>
import { Popup, Icon, DatetimePicker, Toast } from 'vant'
import { computed, ref } from 'vue'
import { dateFormat } from '../utils/common'
import { useStore } from 'vuex'
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  components: {
    [Popup.name]: Popup,
    [Icon.name]: Icon,
    [DatetimePicker.name]: DatetimePicker,
  },
  setup(props, {emit}){
    const store = useStore()
    let popupShow = computed({
      get(){return props.show},
      set(show){emit('update:show', show)}
    })

    let content = ref('')
    let showDatePoput = ref(false)
    let now = new Date()
    let stopDate = ref(null)
    const onDateConfirm = val => {
      stopDate.value = val
      showDatePoput.value = false
    }

    const onSave = () => {
      if (!content.value) {
        Toast('请输入要干的大事')
        return false
      }
      if (!stopDate.value) {
        Toast('请选择截止日期和时间')
        return false
      }
      store.commit('pushTodoItem', {
        stopTime: stopDate.value.getTime(),
        content: content.value
      })
      popupShow.value = false
      content.value = ''
      emit('saved')
    }

    return{
      content,
      showDatePoput,
      minDate: now,
      maxDate: new Date(now.getTime() + 3600 * 24 * 365 * 1000),
      stopDate,
      onDateConfirm,
      dateFormat,
      onSave,
      popupShow
    }
  }
}
</script>

<style lang="less" scoped>
.add-wrapper{
  textarea{
    width: 100%!important;
    height: 80px!important;
    resize: none;
    border: 0;
    padding: 0;
    outline: 0;
  }
  .save{
    color: @primary-color;
  }
}
.content-wrapper{
  padding: 1.5rem;
}
.footer{
  display: flex;
  justify-content: space-between;
  button{
    background: none;
    outline: 0;
    border: 0;
    color: #999;
  }
}
.end-time{
  display: flex;
  align-items: center;
}
</style>